//默认的魔性符号 $
(function (magic) {
    /*========严格模式========*/
    'use strict';
    /*========选择器兼总对象========*/
    window[magic] = function (s) {
        return document.querySelectorAll(s);
    };
    /*========本库依赖方法提前定义========*/
    function extend(t,o) {
        for(var n in o){
            t[n]=o[n] ;
        }
    }
    function type(v) {
        return Object.prototype.toString.apply(v).replace("[object ","").replace("]","");
    }
    function extension(path) {
        var temp= path.split(".");
        return temp[temp.length-1];
    }
    /*========内置方法原型扩展========*/
    String.prototype.charCount = function (c) {//返回字符串中某字符的个数
        var res = this.match(new RegExp(c,'g'));
        return res?res.length:0;
    };

    /*========具有特殊意义的方法========*/
    extend(window[magic],{
        //该方法内的方法在dom树加载完成后执行------------------------$.start(f)----------------参数1：一个方法
        domLoad:function (f) {
            var a = function () {
                document.removeEventListener("DOMContentLoaded",a);
                f();
            };
            document.addEventListener("DOMContentLoaded",a);
        },
        //该方法内的方法在页面所有内容加载完成后执行------------------$.load(f)-----------------参数1：一个方法
        allLoad:function (f) {
            var a = function () {
               window.removeEventListener("load",a);
               f();
            };
            window.addEventListener("load",a);
        },
        //三种文档变化事件,分别为节点插入、节点删除、节点属性改变，第一个参数：回调，第二个参数：是否一次性调用
        domInsert:function (f,remove) {
            var a;
            if (remove) {
                a = function () {document.removeEventListener("DOMNodeInserted", a);f();}
            }
            else {
                a = function () {f();}
            }
            document.addEventListener("DOMNodeInserted", a);
        },
        domRemove:function (f,remove) {
            var a;
            if (remove) {
                a = function () {document.removeEventListener("DOMNodeRemoved", a);f();}
            }
            else {
                a = function () {f();}
            }
            document.addEventListener("DOMNodeRemoved", a);
        },
        attrModify:function (f,remove) {
            var a;
            if (remove) {
                a = function () {document.removeEventListener("DOMAttrModified", a);f();}
            }
            else {
                a = function () {f();}
            }
            document.addEventListener("DOMAttrModified", a);
        },
        //ajax
        ajax:function (url, method, data, callback) {
            var url = url,data = data,name = "",submitdata = "";
            for(name in data){
                submitdata+=name+"="+data[name]+"&";
            }
            submitdata=submitdata.substring(0,submitdata.length-1);
            if(method == "get"){
                url += "?" + submitdata;
                submitdata = "";
            }
            var xhr = new XMLHttpRequest();
            xhr.open(method, url, true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4){
                    if(xhr.status == 200){
                        callback(xhr.responseText);
                    }
                    else{
                        throw new Error("ajax 错误状态号：" + xhr.status);
                    }
                }
            };
            xhr.send(submitdata);
        },
        //ajax get
        get:function (url,callback) {
            var xhr = new XMLHttpRequest();
            xhr.open("get", url, true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4){
                    if(xhr.status == 200){
                        callback(xhr.responseText);
                    }
                    else{
                        throw new Error("ajax 错误状态号：" + xhr.status);
                    }
                }
            };
            xhr.send();
        },
        //using方法用于引入模块（css或js文件）   如果指定入口 用data-main属性 与 requireJS 相同
        using:function(url,callback,t) {
            var head = document.getElementsByTagName('head')[0];
            if(t=="css"||$.extension(url)=="css"){
                var link = document.createElement("link");
                if(type(callback)=="Function"){
                    link.onload = function () {
                        callback();
                    };
                }
                link.rel = "stylesheet";
                link.href = url;
                head.appendChild(link);
            }
            else if(t=="js"||$.extension(url)=="js"){
                var script= document.createElement("script");
                if(type(callback)=="Function"){
                    script.onload = function () {
                        callback();
                    };
                }
                script.src=url;
                head.appendChild(script);
            }
            else {
                window[magic].get(url,function (text) {
                    if(type(callback)=="Function"){
                        callback(text);
                    }
                });
            }
        },
        //增加一个全屏白色div用于加载
        addMask:function () {
            var div = document.createElement("div");
            div.id = "DIVMask";
            div.style.position = "fixed";
            div.style.top = div.style.left = div.style.margin = div.style.padding = "0px";
            div.style.width = window.innerWidth+"px";
            div.style.height = window.innerHeight+"px";
            div.style.backgroundColor = "white";
            div.style.zIndex = 10000;
            document.body.appendChild(div);
        },
        removeMask:function () {
            var div = document.getElementById("DIVMask");
            document.body.removeChild(div);
        },
    });
    /*========工具方法========*/
    extend(window[magic],{
        //对象扩展------------------------$.extend(t,o)----------------参数1：被扩展对象   参数2：一个对象
        extend:extend,
        //返回[a,b]随机数-----------------$.rand(a,b)
        rand:function (a,b) {
            return Math.floor(Math.random()*(b - a + 1) + a);
        },
        //返回时间------------------------$.time.options()------------options  可选(方法) year|month|day|hour|minute|second|millisecond|timestamp|millitimestamp
        time:{
            year:function(){return new Date().getFullYear()},
            month:function(){return new Date().getMonth()+1},
            day:function(){return new Date().getDate()},
            hour:function(){return new Date().getHours()},
            minute:function(){return new Date().getMinutes()},
            second:function(){return new Date().getSeconds()},
            millisecond:function(){return new Date().getMilliseconds()},
            timestamp:function(){return Math.floor(new Date().getTime()/1000)},
            millitimestamp:function(){return new Date().getTime()},
        },
        //each遍历数组或对象执行方法-------$.each(v,f)-----------------意义是抽象for循环，减少代码量，函数式编程的优点
        each: function(v,f) {
            var t = type(v);
            if (t=="Array"||t=="NodeList") {
                for (var i=0;i<v.length;i++) {
                    f(i,v[i]);
                }
            }
            else if(t=="Object"){
                for (var key in v) {
                    f(key,v[key]);
                }
            }
            else{
                throw new TypeError("该对象不支持遍历");
            }
        },
        //返回变量类型--------------------$.type(a)-------------------返回值(字符串)
        // Undefined|Null|Boolean|Number|String|Function|Array|NodeList|Object|RegExp|Date|Error|Symbol
        type:type,
        //返回指定路径文件的扩展名---------$.extension(path)-----------返回值(字符串)
        extension:extension,

    });

    /*========本框架最终执行代码========*/
    //模块化如果指定入口，加载之
    (function () {
        var scriptList =document.getElementsByTagName('script');
        var script = scriptList[scriptList.length - 1];
        var val = script.getAttribute("data-main");
        if(val){
            window[magic].using(val,"js");
        }
    }());
}("$"));//魔性符号在这里定义

/* 还需添加的功能   备忘
* 1、可添加另外的魔性符号 指向当前的符号
*
* 
* */